package org.nvframe.component.render;

import org.newdawn.slick.Animation;
import org.newdawn.slick.SpriteSheet;
import org.nvframe.component.state.Position;
import org.nvframe.entity.Entity;
import org.nvframe.event.EventService;
import org.nvframe.event.eventtype.UpdateEvent;
import org.nvframe.event.eventtype.UpdateListener;
import org.nvframe.event.eventtype.RenderEvent;
import org.nvframe.event.eventtype.RenderListener;
import org.nvframe.exception.NVFrameException;
import org.nvframe.manager.ResourceManager;
import org.nvframe.util.AnimationResource;
import org.nvframe.util.Settings;

/**
 * 
 * @author Nik Van Looy
 */
public class SpriteAnimationRender extends AbstractRender implements UpdateListener, RenderListener {

	private int duration;
	private float direction;
	private boolean relativeDirection;
	
	private Animation animation;
	private SpriteSheet spriteSheet;
	private AnimationResource animationResource;

	public SpriteAnimationRender(String id, Entity owner, Settings settings) throws NVFrameException {
		super(id, owner, settings);
		
		relativeDirection = settings.getBoolean("relativeDirection", true);

		try {
			animationResource = ResourceManager.getInstance().getAnimationResource(settings.getString("animation"));

			duration = settings.getInt("duration", animationResource.getDuration());
			
			spriteSheet = new SpriteSheet(animationResource.getImage(), 
					animationResource.getTileWidth(), 
					animationResource.getTileHeight());

			// TODO get tile properties from resource file (via ResourceManager)!
			animation = new Animation(spriteSheet, duration);
			
			animation.stopAt(animation.getFrameCount()-1);
			//animation.start();
		} catch (NVFrameException e) {
			throw new NVFrameException("cannot load image for ImageRender component");
		}
		
		direction = 0.0f;
		
		EventService.getInstance().addEventListener(this);
	}

	public void start() {
		animation.start();
	}

	public void stop() {
		animation.stop();
	}
	
	@Override
	public void onUpdate(UpdateEvent event) {
		Position position = (Position) owner.getComponent(Position.class);
		
		if(position == null)
			return;
		
		if(relativeDirection)
			spriteSheet.setRotation(position.getDirection() + direction);
		else
			spriteSheet.setRotation(direction);
	}
	
	@Override
	public void onRender(RenderEvent event) {
		Position position = (Position) owner.getComponent(Position.class);
		
		if(position == null)
			return;

		animation.draw(position.getX() - animationResource.getTileWidth() / 2 , 
				position.getY() - animationResource.getTileHeight() / 2);

	}

}
